package com.quan.weixin.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mzlion.easyokhttp.HttpClient;
import com.mzlion.easyokhttp.response.HttpResponse;
import com.quan.weixin.api.API;
import com.quan.weixin.common.WeixinUtil;
import com.quan.weixin.model.Menu;
import com.quan.weixin.model.QrCode;
import com.quan.weixin.model.QrCodeTicket;
import com.quan.weixin.model.ResponseMsg;
import com.quan.weixin.model.SubscribeUser;
import com.quan.weixin.model.UserDetail;
import com.quan.weixin.service.WeixinApiService;
import com.quan.weixin.service.WeixinMenuService;

@Service
public class WeixinApiServiceImpl implements WeixinApiService {
	private static Logger logger = LoggerFactory.getLogger(WeixinApiServiceImpl.class);
	@Autowired
	private WeixinMenuService weixinMenuService;

	@Override
	public ResponseMsg pushMenuToWeiXin(String accessToken) {
		List<Menu> allMenusToWeixin = this.weixinMenuService.getAllMenusToWeixin();

		Map<String, List<Menu>> map = new HashMap<String, List<Menu>>();
		map.put("button", allMenusToWeixin);
		
		//String user_define_menu = "{\"button\":[{\"type\":\"click\",\"name\":\"项目管理\",\"key\":\"20_PROMANAGE\"},{\"type\":\"click\",\"name\":\"机构运作\",\"key\":\"30_ORGANIZATION\"},{\"name\":\"日常工作\",\"sub_button\":[{\"type\":\"click\",\"name\":\"待办工单\",\"key\":\"01_WAITING\"},{\"type\":\"click\",\"name\":\"已办工单\",\"key\":\"02_FINISH\"},{\"type\":\"click\",\"name\":\"我的工单\",\"key\":\"03_MYJOB\"},{\"type\":\"click\",\"name\":\"公告消息箱\",\"key\":\"04_MESSAGEBOX\"},{\"type\":\"click\",\"name\":\"签到\",\"key\":\"05_SIGN\"}]}]}";
		
		ResponseMsg msg = WeixinUtil.doPost(API.get(API.MENU_CREATE_URL, accessToken), map).asBean(ResponseMsg.class);
		return msg;
	}

	@Override
	public SubscribeUser getSubscribeUserList(String accessToken, String next_openid) {
		String asString = WeixinUtil.doGet(API.get(API.USER_LIST_URL, accessToken, StringUtils.isNotBlank(next_openid) ? next_openid : "")).asString();
		SubscribeUser subscribeUser = JSON.parseObject(asString, SubscribeUser.class) ;
		
		if(subscribeUser.getData() != null) {
			JSONObject parseObject2 = JSON.parseObject(asString);
			JSONObject parseObject3 = JSON.parseObject(parseObject2.get("data").toString());
			JSONArray parseArray = JSON.parseArray(parseObject3.get("openid").toString()) ;
			List<String> openids = new ArrayList<String>() ;
			for (Object openid : parseArray) {
				openids.add(openid.toString());
			}
			subscribeUser.setData(openids);
		}
		
		return subscribeUser;
	}

	@Override
	public UserDetail getUserDetail(String accessToken, String openid) {
		UserDetail detail = WeixinUtil.doGet(API.get(API.USER_DETAIL_URL, accessToken, openid)).asBean(UserDetail.class) ;
		return detail;
	}

	@Override
	public String showQRCodeTemp(String accessToken, Long expire_seconds, String action_name, Object sceneValue) {
		//获取创建二维码ticket
		String qrCodeTicket = null ;
		if(null == expire_seconds) {
			expire_seconds = 604800L ;//7天
		}
		
		if("QR_SCENE".equals(action_name)) {//整形参数
			if(null != sceneValue) {//带场景值
				try {
					qrCodeTicket = QrCodeTicket.sceneIntVal(expire_seconds, action_name, Integer.parseInt(sceneValue.toString()));
				} catch (NumberFormatException e) {
					return "场景值参数需为整形" ;
				}
			} else {
				qrCodeTicket = QrCodeTicket.sceneIntVal(expire_seconds, action_name);
			}
			logger.debug("创建二维码ticket：{}", qrCodeTicket);
		} 
		if("QR_STR_SCENE".equals(action_name)) {//字符参数
			if(null != sceneValue) {//带场景值
				qrCodeTicket = QrCodeTicket.sceneStrVal(expire_seconds, action_name, sceneValue.toString());
			} else {
				qrCodeTicket = QrCodeTicket.sceneStrVal(expire_seconds, action_name);
			}
		}
		if(null != qrCodeTicket) {
			try {
				HttpResponse response = HttpClient.textBody(API.get(API.QR_CODE_TICKET_URL, accessToken)).json(qrCodeTicket).execute();
				QrCode qrCode = response.asBean(QrCode.class) ;
				logger.debug("获取二维码Ticket：{}", qrCode);
				if(null != qrCode) {
					//返回二维码图片的URL
					String qrCodeUrl = API.get(API.QR_CODE_SHOW_URL, URLEncoder.encode(qrCode.getTicket(), "UTF-8")) ;
					logger.debug("临时二维码图片URL：{}", qrCodeUrl);
					return qrCodeUrl ;
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public String showQRCodeForever(String accessToken, String action_name, Object sceneValue) {
		//获取创建二维码ticket
		String qrCodeTicket = null ;
		
		//整形参数
		if("QR_LIMIT_SCENE".equals(action_name)) {
			if(null != sceneValue) {//带场景值
				try {
					qrCodeTicket = QrCodeTicket.sceneIntVal(action_name, Integer.parseInt(sceneValue.toString()));
				} catch (NumberFormatException e) {
					return "场景值参数需为整形" ;
				}
			} else {
				qrCodeTicket = QrCodeTicket.sceneIntVal(action_name);
			}
			logger.debug("创建二维码ticket：{}", qrCodeTicket);
		}
		if("QR_LIMIT_STR_SCENE".equals(action_name)) {
			if(null != sceneValue) {//带场景值
				qrCodeTicket = QrCodeTicket.sceneStrVal(action_name, sceneValue.toString());
			} else {
				qrCodeTicket = QrCodeTicket.sceneStrVal(action_name);
			}
		}
		if(null != qrCodeTicket) {
			try {
				HttpResponse response = HttpClient.textBody(API.get(API.QR_CODE_TICKET_URL, accessToken)).json(qrCodeTicket).execute();
				QrCode qrCode = response.asBean(QrCode.class) ;
				logger.debug("获取二维码Ticket：{}", qrCode);
				if(null != qrCode) {
					//返回二维码图片的URL
					String qrCodeUrl = API.get(API.QR_CODE_SHOW_URL, URLEncoder.encode(qrCode.getTicket(), "UTF-8")) ;
					logger.debug("永久二维码图片URL：{}", qrCodeUrl);
					return qrCodeUrl ;
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public JSONObject deleteMedia(String accessToken, String mediaId) {
		String delMediaUrl = API.get(API.DELETE_MEDIA_URL, accessToken) ;
		Map<String, String> params = new HashMap<String, String>() ;
		params.put("media_id", mediaId) ;
		
		String asString = WeixinUtil.doPost(delMediaUrl, params).asString();
		return JSON.parseObject(asString);
	}

	@Override
	public boolean deleteMedia(String accessToken, List<String> mediaIds) {
		for (String mediaId : mediaIds) {
			String delMediaUrl = API.get(API.DELETE_MEDIA_URL, accessToken) ;
			Map<String, String> params = new HashMap<String, String>() ;
			params.put("media_id", mediaId) ;
			
			String asString = WeixinUtil.doPost(delMediaUrl, params).asString();
			JSONObject parseObject = JSON.parseObject(asString);
			Integer errcode = parseObject.getInteger("errcode") ;
			if(errcode == 0) {
				logger.debug("删除永久图文素材成功,MediaId：{}", mediaId );
			} else {
				logger.debug("删除永久图文素材失败,MediaId：{}", parseObject.toString() );
			}
		}
		
		return true;
	}

}
